# encoding: utf-8

class PostsController < ApplicationController

	before_filter :load_sidebar
	before_filter :require_moderator, :except => [:index, :show, :feed, :category]
	before_filter :do_index, :only => [:index, :category, :show]
	
	# pocetna stranica
	def index
		@posts = Post.paginate :page => params[:page], :per_page => 4,:order => 'created_at DESC'
		@meta_description = "Cilj nam je okupiti ljude zainteresirane za web dizajn i programiranje i pružiti im mogućnost rada u timu na većim projektima i upoznavanja ljudi sličnih interesa. "
	end

	# rss feed stranice
	def feed
		@posts = Post.all(:order => "created_at DESC", :limit => 20);
		
		respond_to do |format|
      format.rss { render :layout => false } #index.rss.builder
    end
	end

	# prikaz svih postova u admin sucelju
	def index_admin
		@posts = Post.order("created_at DESC").all
		@categories = Category.all
	end
	
	# prikaz pojedine kategorije
	def category
		@category = Category.where( :slug => params[:category]).first
		@posts = @category.posts.paginate :page => params[:page], :per_page => 4,:order => 'created_at DESC'

		@meta_title = @category.name + " | Udruga dizajnera i programera"
		@meta_descripton = @category.description
	end

	# prkaz pojedinog posta
	def show
		@post = Post.where( :slug => params[:slug] ).first

		unless @post.category.slug == params[:category]
			redirect_to root_url
		end

		@meta_description = @post.content.gsub(/<\/?[^>]*>/, "")[0,200]
		@meta_title = @post.title + " | " + @post.category.name
	end

	# obrazac za stvaranje novog posta
	def new
		@post = Post.new
		@categories = Category.all
		@images = Image.order("created_at DESC").all
	end

	# obrazac za uredjivanje posta
	def edit
		@post = Post.find( params[:id] )
		@categories = Category.all
		@images = Image.order("created_at DESC").all
	end

	# stvaranje novog posta
	def create
		@post = Post.new( params[:post] )
		@post.member_id = current_member.id

		if @post.save
			redirect_to posts_path
		else
			@categories = Category.all
			render :action => 'new'
		end
	end

	# uredjivanje posta
	def update
		@post = Post.find( params[:id])

		if @post.update_attributes( params[:post] )
			redirect_to frontend_post_path(@post.category.slug,@post.slug) 
		else
			@categories = Category.all
			render :action => :edit
		end
	end

	# brisanje posta
	def destroy
		post = Post.find( params[:id] )
		post.destroy
		redirect_to posts_path
	end
end
